﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace DataShow.forecasters
{
    public partial class admin : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btn_check_all_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow item in gv_result.Rows)
            {
                (item.FindControl("Select") as CheckBox).Checked = true;
            }
        }

        protected void btn_delete_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow item in gv_result.Rows)
            {
                CheckBox cbx = new CheckBox();
                cbx = item.FindControl("Select") as CheckBox;
                if (cbx.Checked)
                {
                    Label lblid = item.FindControl("ID") as Label;
                    string id = lblid.Text.Trim();
                    Label lblUsername = item.FindControl("username") as Label;
                    string username = lblUsername.Text;
                    Delete(id, username);
                }
            }
            Common.RegisterScriptAtPageLast(Page, "alert('删除成功！')");
            //Response.Write("<script>alert('删除成功！')</script>");
            Bind();
        }

        #region 删除预报员
        /// <summary>
        /// 删除预报员
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="username"></param>
        private void Delete(string userid, string username)
        {
            codeDAL.SqlHelper helper = new codeDAL.SqlHelper();
            string sql = "delete from account_forecaster where id=" + userid;
            helper.ExecuteNonQuery(sql, null);
            sql = "drop table " + username + "_UFore";
            helper.ExecuteNonQuery(sql, null);
        } 
        #endregion

        protected void btn_search_all_Click(object sender, EventArgs e)
        {
            Bind();
        }

        #region 添加预报员
        /// <summary>
        /// 添加预报员
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_add_Click(object sender, EventArgs e)
        {
            bool isEdit=false;
            string username = txt_username.Text.Trim();
            string fid = lbl_fid.Text;
            string password = txt_password.Text.Trim();
            string name = txt_name.Text.Trim();
            string birth = txt_birthday.Text.Trim();
            bool isForecaster = !cbx_isadmin.Checked;
            string forecasterNum = txt_forecasterID.Text.Trim();
            string gender = ddl_gender.SelectedValue;
            bool isActive = cbx_active.Checked;
            codeDAL.SqlHelper helper = new codeDAL.SqlHelper();
            string sql = "";
            if ((sender as Button).Text == "修改")
            {
                isEdit = true;
                sql = "update account_forecaster set username=@username,password=@password,is_active=@isActive,name=@name,sex=@sex,birth=@birth,is_forcaster=@is_forecaster,forcaster_number=@forecasternum where id='"+fid+"'";
            }
            else
            {
                sql = "insert into account_forecaster values(@username,@password,'',@isActive,@name,@sex,@birth,@is_forecaster,@forecasternum)";
            }
            if (CheckUserNotUnique(username) && !isEdit)
            {
                Common.RegisterScriptAtPageLast(Page, "alert('用户名重复！')");
                //Response.Write("<script>alert('用户名重复')</script>");
                return;
            }
            SqlParameter[] param = new SqlParameter[] 
            {
                new SqlParameter("@username",username),
                new SqlParameter("@password",password),
                new SqlParameter("@isActive",isActive),
                new SqlParameter("@name",name),
                new SqlParameter("@sex",gender),
                new SqlParameter("@birth",birth),
                new SqlParameter("@is_forecaster",isForecaster),
                new SqlParameter("@forecasternum",forecasterNum)
            };
            if (helper.ExecuteNonQuery(sql, param) > 0)
            {
                txt_birthday.Text = DateTime.Now.ToString("yyyy-MM-dd");
                txt_forecasterID.Text = "";
                txt_name.Text = "";
                txt_password.Text = "";
                txt_username.Text = "";
                cbx_active.Checked = false;
                cbx_isadmin.Checked = false;
                if (!isEdit)
                {
                    param = new SqlParameter[] { new SqlParameter("@name", username + "_UFore") };
                    helper.ExecuteNonQuery("CreateUserTable", param, System.Data.CommandType.StoredProcedure);
                }
                Common.RegisterScriptAtPageLast(Page, "alert('" + (isEdit == true ? "修改成功" : "新增成功") + "')");
                //Response.Write("<script>alert('"+(isEdit==true?"修改成功":"新增成功")+"')</script>");
                Bind();
                btn_add.Text = "添加";
                txt_username.Enabled = true; 
            }
            else
            {
                Common.RegisterScriptAtPageLast(Page, "alert('添加失败')");
                //Response.Write("<script>alert('添加失败')</script>");
                return;
            }
        }
        private bool CheckUserNotUnique(string username)
        {
            string sql = "select * from [account_forecaster] where username='"+username+"'";
            return (new codeDAL.SqlHelper().ExecuteQuery(sql,System.Data.CommandType.Text).Rows.Count > 0);
        }
        #endregion

        private void Bind()
        {
            string sql = "select * from account_forecaster";
            gv_result.DataSource = new codeDAL.SqlHelper().ExecuteQuery(sql, System.Data.CommandType.Text);
            gv_result.DataBind();
        }


        protected void btn_update_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow item in gv_result.Rows)
            {
                CheckBox cbx = new CheckBox();
                cbx = item.FindControl("Select") as CheckBox;
                if (cbx.Checked)
                {
                    Label id = item.FindControl("ID") as Label;
                    CheckBox cbxactive = item.FindControl("cbx_active") as CheckBox;
                    CheckBox cbxisfore = item.FindControl("cbx_isf") as CheckBox;
                    Update(id.Text, cbxactive.Checked, cbxisfore.Checked);
                }
            }
            Bind();
        }


        private void Update(string id,bool isactive,bool isfore)
        {
            string sql = "update account_forecaster set is_active=@active,is_forcaster=@isf  where id=" + id;
            SqlParameter[] para = new SqlParameter[]
            {
                new SqlParameter("@active",isactive),
                new SqlParameter("@isf",isfore)
            };
            new codeDAL.SqlHelper().ExecuteNonQuery(sql, para);
        }


        /// <summary>
        /// 更新预报员填充数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lb_edit_Click(object sender, EventArgs e)
        {
            string fid = (sender as LinkButton).CommandArgument;
            lbl_fid.Text = fid;
            string sql = "select * from account_forecaster where id=" + fid;
            DataTable dt = new codeDAL.SqlHelper().ExecuteQuery(sql, CommandType.Text);
            if (dt.Rows.Count > 0)
            {
                var row = dt.Rows[0];
                txt_username.Text = row["username"].ToString();
                txt_password.Text = row["password"].ToString();
                txt_name.Text = row["name"].ToString();
                txt_forecasterID.Text = row["forcaster_number"].ToString();
                txt_birthday.Text = row["birth"].ToString();
                cbx_active.Checked = Convert.ToBoolean(row["is_active"]);
                cbx_isadmin.Checked = !Convert.ToBoolean(row["is_forcaster"]);
                ddl_gender.SelectedValue = row["sex"].ToString();
                btn_add.Text = "修改";
                txt_username.Enabled = false;
            }
        }
    }
}